package com.gitee.feizns.quickstart.ding.talk.api.v10.yida.forms.instances;

import com.aliyun.dingtalkyida_1_0.Client;
import com.aliyun.dingtalkyida_1_0.models.CreateOrUpdateFormDataHeaders;
import com.aliyun.dingtalkyida_1_0.models.CreateOrUpdateFormDataRequest;
import com.aliyun.dingtalkyida_1_0.models.CreateOrUpdateFormDataResponse;
import com.aliyun.teautil.models.RuntimeOptions;
import com.gitee.feizns.quickstart.ding.talk.client.Clients;
import com.gitee.feizns.quickstart.ding.talk.domain.SearchCondition;
import com.gitee.feizns.quickstart.jackson.JsonUtils;
import lombok.SneakyThrows;

import java.util.List;

/**
 * 插入或更新
 * @author feizns
 * @since 2024/7/1
 */
public class InsertOrUpdate {

    /**
     * 执行
     * @param accessToken 访问令牌
     * @param appType 应用类型
     * @param systemToken 系统令牌
     * @param formUuid 表格 UUID
     * @param userid 乌塞里德
     * @param data 数据
     * @param noExecuteExpression 无执行表达式
     * @param searchConditions 搜索条件
     * @return {@link List }<{@link String }>
     */
    @SneakyThrows
    public static List<String> execute(String accessToken, String appType, String systemToken, String formUuid, String userid, String formDataJson, Boolean noExecuteExpression, SearchCondition... searchConditions) {
        Client client = Clients.get(Client.class);
        CreateOrUpdateFormDataHeaders headers = headers(accessToken);
        CreateOrUpdateFormDataRequest req = request(appType, systemToken, formUuid, userid, formDataJson, noExecuteExpression, searchConditions);
        CreateOrUpdateFormDataResponse resp = client.createOrUpdateFormDataWithOptions(req, headers, new RuntimeOptions());
        return resp.getBody().getResult();
    }

    /**
     * 请求
     * @param appType 应用类型
     * @param systemToken 系统令牌
     * @param formUuid 表格 UUID
     * @param userid 乌塞里德
     * @param formDataJson 从 JSON 列表
     * @param noExecuteExpression 无执行表达式
     * @param searchConditions 搜索条件
     * @return {@link CreateOrUpdateFormDataRequest }
     */
    public static CreateOrUpdateFormDataRequest request(String appType, String systemToken, String formUuid, String userid, String formDataJson, Boolean noExecuteExpression, SearchCondition... searchConditions) {
        return new CreateOrUpdateFormDataRequest()
                .setNoExecuteExpression(noExecuteExpression)
                .setFormUuid(formUuid)
                .setSearchCondition(JsonUtils.toJson(searchConditions))
                .setAppType(appType)
                .setFormDataJson(formDataJson)
                .setSystemToken(systemToken)
                .setUserId(userid);
    }

    /**
     * 头
     * @param accessToken 访问令牌
     * @return {@link CreateOrUpdateFormDataHeaders }
     */
    public static CreateOrUpdateFormDataHeaders headers(String accessToken) {
        CreateOrUpdateFormDataHeaders headers = new CreateOrUpdateFormDataHeaders();
        headers.xAcsDingtalkAccessToken = accessToken;
        return headers;
    }

}
